// Learn TypeScript:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

interface IAutoAction extends cc.Component {
    autoAction: () => void;
}

export default class AutoActions {
    private aa: IAutoAction | cc.Component;
    private action: () => void;
    private actionThisArg: any;

    constructor(
        autoAction: IAutoAction | cc.Component,
        action?: () => void,
        actionThisArg?: any
    ) {
        this.aa = autoAction;

        this.actionThisArg = actionThisArg;

        if (!action) {
            if (!actionThisArg) {
                this.action = () => (this.aa as IAutoAction).autoAction.call(this.aa);
            } else {
                this.action = () => (this.aa as IAutoAction).autoAction.call(this.actionThisArg);
            }
        } else {
            if (!actionThisArg) {
                this.action = () => action.call(this.aa);
            } else {
                this.action = () => action.call(this.actionThisArg);
            }
        }
    }

    public start(interval?: number): AutoActions {
        this.aa.schedule(this.action, interval || 0, cc.macro.REPEAT_FOREVER);
        return this;
    }

    public stop(): AutoActions {
        this.aa.unschedule(this.action);
        return this;
    }
    public destroy() {
        this.stop();
        this.aa = null;
        this.action = null;
        this.actionThisArg = null;
    }
}
